/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package session

import (
	"encoding/gob"
	"bytes"
)

type Session struct {
	id string
	values map[string]string
	changed bool
}

func (rs *Session) ID() string {
	return rs.id
}

// 根据 key 获取 session 数据
func (rs *Session) Get(key string) string {
	return rs.values[key]
}

// 设置 session 数据
func (rs *Session) Set(key, value string) {
	rs.values[key] = value
	rs.changed = true
}

// 删除 session 数据
func (rs *Session) Del(key string) {
	if _, ok := rs.values[key]; ok {
		delete(rs.values, key)
		rs.changed = true
	}

}

// 获得所有 session 数据
func (rs *Session) Values() map[string]string {
	return rs.values
}

// 清除所有 session 数据
func (rs *Session) Drop() {
	rs.changed = true
	rs.values = make(map[string]string)
}

// 根据 key 获取并删除数据
func (rs *Session) Flash(key string) string {
	value := rs.Get(key)
	rs.Del(key)
	return value
}

func Unmarshal(data []byte) (values map[string]string, err error) {
	decoder := gob.NewDecoder(bytes.NewBuffer(data))
	err = decoder.Decode(&values)
	if err != nil {
		return nil, err
	} else {
		return values, nil
	}
}

func Marshal(values map[string]string) (data []byte, err error) {
	buf := bytes.NewBuffer(nil)
	encoder := gob.NewEncoder(buf)
	err = encoder.Encode(values)
	if err != nil {
		return nil, err
	} else {
		return buf.Bytes(), nil
	}
}